package cn.sjlink.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.Random;

/**
 * Created by zano on 2017/3/20.
 */
@Component
public class UploadClietUtil {
    private final Logger logger = Logger.getLogger(getClass());
    private String endpoint = ConfigUtil.get("endpoint");
    private String accessKeyId = ConfigUtil.get("accessKeyId");
    private String accessKeySecret = ConfigUtil.get("accessKeySecret");
    private OSSClient ossClient;
    //空间
    private String bucketName = ConfigUtil.get("bucketName") ;
    //文件存储目录
    private String filedir =DateUtil.getSNowDate()+"/";
    public UploadClietUtil() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }
    //初始化
    public void init() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }
    /**
     * 销毁
     */
    public void destory() {
        ossClient.shutdown();
    }

    /**
     * 上传图片
     *
     * @param url
     */
    public void uploadImg2Oss(String url) {
        File fileOnServer = new File(url);
        FileInputStream fin;
        try {
            fin = new FileInputStream(fileOnServer);
            String[] split = url.split("/");
            this.uploadFile2OSS(fin, split[split.length - 1]);
        } catch (FileNotFoundException e) {
           e.printStackTrace();
        }
    }


    public String uploadImg2Oss(MultipartFile file) {
        if (file.getSize() > 10*1024 * 1024) {
            return "图片大小不能超过10M";
        }
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        Random random = new Random();
        String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(inputStream, name);
            return name;
        } catch (Exception e) {
            e.printStackTrace();
            return "服务器异常";
        }
    }

    /**
     * 获得图片路径
     *
     * @param fileUrl
     * @return
     */
    public String getImgUrl(String fileUrl) {
        if (!StringUtils.isEmpty(fileUrl)) {
            String[] split = fileUrl.split("/");
            return this.getUrl(this.filedir + split[split.length - 1]);
        }
        return null;
    }

    /**
     * 上传到OSS服务器  如果同名文件会覆盖服务器上的
     *
     * @param instream 文件流
     * @param fileName 文件名称 包括后缀名
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public String uploadFile2OSS(InputStream instream, String fileName) {
        String ret = "";
        String url = "";
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //上传文件
            PutObjectResult putResult = ossClient.putObject(bucketName,filedir+fileName, instream);
            ret = putResult.getETag();
            url = getUrl(filedir + fileName);
        } catch (IOException e) {
           e.printStackTrace();
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return url;
    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase("gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase("jpeg") ||
                FilenameExtension.equalsIgnoreCase("jpg") ||
                FilenameExtension.equalsIgnoreCase("png")) {
            return "image/jpeg";
        }
        if(FilenameExtension.equalsIgnoreCase("xls")){
            return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        }


        return "image/jpeg";
    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public String getUrl(String key) {
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }

    public String getFiledir() {
            return filedir;

    }
    public void setFiledir(String filedir) {
        if(filedir!=null && StringUtils.isNotEmpty(filedir)) {
            this.filedir = filedir;
        }else{
            this.filedir = ConfigUtil.get("filedir");
        }
    }
    /**
     * 视频上传
     */
    public Result uploadVideoStream(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        Random random = new Random();
        String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
        InputStream inputStream = null;
        try {
             inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
       /* if(inputStream!=null){
            UploadStreamRequest request = new UploadStreamRequest(accessKeyId,accessKeySecret,originalFilename,filedir+name,inputStream);
            //回调的url
            //request.setCallback("http://callback.sample.com");
            //封面图片
            //request.setCoverURL("http://cover.sample.com/sample.jpg");
            request.setStorageLocation("outin-7495f86a5f6211e9b5e300163e1c9256.oss-cn-beijing.aliyuncs.com");
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);

            if (response.isSuccess()) {
                GetMezzanineInfoResponse mezzanineInfo = getMezzanineInfo(response.getVideoId());
                Map<String,String> result = new HashMap<>();
                result.put("videoId",response.getVideoId());
                result.put("fileUrl",mezzanineInfo.getMezzanine().getFileURL().split("\\?")[0]);
                logger.info("VideoId=" + response.getVideoId() + "\n");
                return new Result(true,"上传成功",result);
            } else {
            *//* 如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因 *//*
                logger.info("VideoId=" + response.getVideoId() + "\n");
                logger.info("ErrorCode=" + response.getCode() + "\n");
                logger.info("ErrorMessage=" + response.getMessage() + "\n");
                return new Result(false,"上传失败");
            }
        }*/
        return new Result(false,"上传失败");
    }


}
